package com.mrt.chatgpt.data.trigger.job;


import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.google.common.eventbus.EventBus;
import com.mrt.chatgpt.data.domain.order.service.IOrderService;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Author 86135
 * @Date 2024/3/26 14:45
 * @Description
 * @Version 1.0
 * @快捷键 getterANDsetter ALT+Insert
 * @快捷键 Ctrl+/或者Ctrl+Shift+/都可以快速注释
 * @快捷键 Ctrl+D 快速复制代码
 * @“ctrl+r”快捷键,用于当前文件内容替换,指的是在当前打开的文件中替换匹配的字符,只操作一个文件;
 * @ALT+鼠标左键 整列编辑
 * @快捷键提示 ALT+Enter
 * @快捷键 快速写注释：在方法函数上方输入/** 然后回车
 * @快捷键 Ctrl+O，选择重写的方法
 * @快捷键 ALT+INSERT
 */

/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description 检测未接收到或未正确处理的支付回调通知
 * @create 2023-10-05 19:52
 */
@Slf4j
@Component()
public class NoPayNotifyOrderJob {
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private IOrderService orderService;
    //TODO  待修改
    @Autowired(required = false)
    private NativePayService payService;
    @Resource
    private EventBus eventBus;

    //TODO  待修改
    @Value("${wxpay.config.mchid}")
    private String mchid;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Scheduled(cron = "0 0/1 * * * ?")
    public void exec(){
        try {
            List<String> orderIds = orderService.queryNoPayNotifyOrder();
            if (orderIds.isEmpty()) {
                log.info("定时任务，订单支付状态更新，暂无未更新订单 orderId is null");
                return;
            }
            for(String orderId : orderIds){
                // 构造请求参数以调用接口
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel model = new AlipayTradeQueryModel();
                model.setOutTradeNo(orderId);
                request.setBizModel(model);
                AlipayTradeQueryResponse response = alipayClient.execute(request);
                String responseBody = response.getBody();
                JSONObject jsonObject = new JSONObject(responseBody);
                JSONObject tradeQueryResponse = jsonObject.getJSONObject("alipay_trade_query_response");
                String tradeStatus = tradeQueryResponse.getString("trade_status");
                if(tradeStatus ==" TRADE_SUCCESS"){
                    String tradeNo = tradeQueryResponse.getString("trade_no");
                    String totalAmountS = tradeQueryResponse.getString("total_amount");
                    //Integer intValue = Integer.parseInt(totalAmountS); // 转换为int类型
                    String sendPayDate = tradeQueryResponse.getString("send_pay_date");
                 //支付单号
                BigDecimal totalAmount = new BigDecimal(totalAmountS).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                boolean isSuccess = orderService.changeOrderPaySuccess(orderId, tradeNo, totalAmount, dateFormat.parse(sendPayDate));
                if (isSuccess) {
                    // 发布消息
                    eventBus.post(orderId);
                }
                }else {
                    log.info("定时任务，订单支付状态更新，当前订单未支付 orderId is {}", orderId);
                    continue;
                }
                if(response.isSuccess()){
                    log.info("调用成功");
                } else {
                    log.info("调用失败");
                }
            }
        }catch (Exception e){
            log.error("定时任务，订单支付状态更新失败", e);
        }
    }
//    public void exec(){
//        try {
//            if (null == payService) {
//                log.info("定时任务，订单支付状态更新。应用未配置支付渠道，任务不执行。");
//                return;
//            }
//            List<String> orderIds = orderService.queryNoPayNotifyOrder();
//            if (orderIds.isEmpty()) {
//                log.info("定时任务，订单支付状态更新，暂无未更新订单 orderId is null");
//                return;
//            }
//            for(String orderId : orderIds){
//                //查询结果
//                //TODO：待修改
//                QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
//                request.setMchid(mchid);
//                request.setOutTradeNo(orderId);
//                Transaction transaction = payService.queryOrderByOutTradeNo(request);
//                if (!Transaction.TradeStateEnum.SUCCESS.equals(transaction.getTradeState())) {
//                    log.info("定时任务，订单支付状态更新，当前订单未支付 orderId is {}", orderId);
//                    continue;
//                }
//                //支付单号
//                String transactionId = transaction.getTransactionId();
//                Integer total = transaction.getAmount().getTotal();
//                BigDecimal totalAmount = new BigDecimal(total).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
//                String successTime = transaction.getSuccessTime();
//                boolean isSuccess = orderService.changeOrderPaySuccess(orderId, transactionId, totalAmount, dateFormat.parse(successTime));
//                if (isSuccess) {
//                    // 发布消息
//                    eventBus.post(orderId);
//                }
//            }
//        }catch (Exception e) {
//            log.error("定时任务，订单支付状态更新失败", e);
//        }
//    }
}
